package com.yaoweigroup.community.ui.home;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.BBSTitle;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.LoginUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 发帖
 * 
 * @author xi
 * 
 */
public class PostEditActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private EditText title_et;
	private EditText content_et;
	private Button post_btn;
	private BBSTitle title;
	private ObjectMapper mapper;
	private SharePreferenceUtil util;

	private Dialog dialog;

	public final int POST_SUCCESS = 0x2210;
	public final int POST_FAIL = POST_SUCCESS + 1;
	public final int NEED_LOGIN = POST_SUCCESS + 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		util = new SharePreferenceUtil(this, Constant.prf);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_post_edit);

		mapper = new ObjectMapper();
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		title = (BBSTitle) getIntent().getSerializableExtra("titles");
		title_et = (EditText) findViewById(R.id.title_et);
		content_et = (EditText) findViewById(R.id.content_et);
		post_btn = (Button) findViewById(R.id.post_btn);
		post_btn.setOnClickListener(this);

		dialog = DialogUtil.createWaitDialog(this, "提交中..");

		type = getIntent().getIntExtra("type", 0);
		if (type == 1) {
			postId = getIntent().getStringExtra("id");
			String title = getIntent().getStringExtra("title");
			title_et.setText(title);
			title_et.setEnabled(false);
		}
	}

	private String postId = null;
	private int type = 0;// 0 是发贴 1是跟帖

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.post_btn:
			if (type == 0) {
				doPost();
			} else {
				postReply();
			}

			break;
		}
	}

	private void doPost() {

		if (title == null) {
			Toast.makeText(this, "发帖失败!", 500).show();
			return;
		}
		String titleStr = title_et.getText().toString();
		String contentStr = content_et.getText().toString();
		if (titleStr.length() == 0 || contentStr.length() == 0) {
			Toast.makeText(this, "标题或内容不能为空", 500).show();
			return;
		}

		UserInfo user = (UserInfo) util.loadObject("user");
		if (user == null) {
			Toast.makeText(this, "请先登录再操作!", 500).show();
			return;
		}
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("Title", titleStr);
		jsonUtil.add("Content", contentStr);
		jsonUtil.add("typeid", title.getId());
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json;charset=UTF-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.setPost, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(POST_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								handler.sendEmptyMessage(POST_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(POST_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(POST_FAIL);
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case POST_FAIL:
				dialog.dismiss();
				Toast.makeText(PostEditActivity.this, "发帖失败", 500).show();
				break;
			case POST_SUCCESS:
				dialog.dismiss();
				finish();
				break;
			case NEED_LOGIN:
				LoginUtil
						.isLoginSuccess(PostEditActivity.this, handler, mapper);
				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				Toast.makeText(PostEditActivity.this, "发帖失败", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				if (type == 0) {
					doPost();
				} else {
					postReply();
				}

				break;
			}
		};
	};

	private void postReply() {

		String titleStr = title_et.getText().toString();
		String contentStr = content_et.getText().toString();
		if (titleStr.length() == 0 || contentStr.length() == 0) {
			Toast.makeText(this, "标题或内容不能为空", 500).show();
			return;
		}
		UserInfo user = (UserInfo) util.loadObject("user");
		if (user == null) {
			Toast.makeText(this, "你未登录不能发帖!", 500).show();
			return;
		}
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", user.getUid());
		jsonUtil.add("bid", postId);
		jsonUtil.add("sid", "0");
		jsonUtil.add("Content", contentStr);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json;charset=UTF-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.setreplypost, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(POST_SUCCESS);
							} else if (state == 10000) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								handler.sendEmptyMessage(POST_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(POST_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(POST_FAIL);
					}
				});
	}
}
